#include "myinet.h"
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include "tools.h"

void error_msg(const char* msg, const char* s4perrno){
    write(STDERR_FILENO, msg, strlen(msg));
    perror(s4perrno);
}

int
main(int argc, char** argv){

    int sockfd;
    int newsockfd;
    int portNumber;

    char buffer[256];

    if (argc < 2){
        printf("Usage: %s <port>\n", argv[0]);
        error_exit("please use the above format", NULL);
    }

    portNumber = atoi(argv[1]);

    sockfd = getTcpServerSocket(portNumber);
    if (sockfd < 0)
    {
        error_exit("failed to get socket", "");
    }
    printf("listening to socket on port: %d\n", portNumber);

    struct sockaddr_in cli_addr;
    socklen_t clilen;
    clilen = sizeof(cli_addr);
    newsockfd = accept(sockfd,
            (struct sockaddr*)&cli_addr,
            &clilen);

    if(newsockfd < 0){
        error_msg("error accepting message\n", "accept");
        return -1;
    }
    printf("received one connection from %s:%d\n",
            inet_ntoa(cli_addr.sin_addr),
            portNumber);

    bzero(buffer, sizeof(buffer));

    puts("reading from socket");
    int n = 0;
    n = read(newsockfd, buffer, sizeof(buffer));
    if (n < 0){
        error_msg("error read\n", "read");
        return -1;
    }

    printf("Here is the message: %s", buffer);

    puts("-----write back to client-----");
    const char* s = "gotcha";
    puts(s);

    n = write(newsockfd, s, strlen(s));

    if (n < 0)
    {
        error_msg("error write back to socket", "write");
        return -1;
    }

    close(newsockfd);
    close(sockfd);

    return 0;
}
